package com.dlc.felear.xiaoensale.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.adapter.OperatorItemAdapter;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.customView.ConfirmDialog;
import com.dlc.felear.xiaoensale.customView.DoubleSelectDialog;
import com.dlc.felear.xiaoensale.customView.SelectCatgerDialog;
import com.dlc.felear.xiaoensale.customView.SingleInputDialog;
import com.dlc.felear.xiaoensale.customView.TextInputDialog;
import com.dlc.felear.xiaoensale.dao.CookingMenuDao;
import com.dlc.felear.xiaoensale.dao.LocalUserDao;
import com.dlc.felear.xiaoensale.dao.MenuFoodMaterialDao;
import com.dlc.felear.xiaoensale.dao.OperatorDao;
import com.dlc.felear.xiaoensale.deviceControlSf.OperatorAutoHandle;
import com.dlc.felear.xiaoensale.deviceUtil.TopbarHelper;
import com.dlc.felear.xiaoensale.entity.CookingMenu;
import com.dlc.felear.xiaoensale.entity.LocalUser;
import com.dlc.felear.xiaoensale.entity.MenuFoodMaterial;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.helper.CookingMenuMangerHelper;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.helper.Session;
import com.dlc.felear.xiaoensale.utils.NumToStringUtil;
import com.dlc.felear.xiaoensale.utils.TimeUtils;
import com.dlc.felear.xiaoensale.utils.UuidUtil;
import com.itdlc.android.library.base.BaseActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 菜谱微调界面
 */
public class MiroEditMenuActivity extends BaseActivity implements View.OnTouchListener, TextInputDialog.TextInputDialogCallback,
        SelectCatgerDialog.SelectCatgerDialogCallback,
        ConfirmDialog.ConfirmDialogCallback, DoubleSelectDialog.DoubleSelectCallback, SingleInputDialog.SingleDialogCallback {
    private static final String TAG = "MiroEditMenuActivity";
    private static final int GZ_1 = 1;
    private static final int GZ_2 = 2;
    private static final int GZ_3 = 3;
    private static final int GZ_4 = 4;
    private static final int GZ_5 = 5;
    @BindView(R.id.et_name_1)
    EditText etName1;
    @BindView(R.id.et_name_2)
    EditText etName2;
    @BindView(R.id.et_name_3)
    EditText etName3;
    @BindView(R.id.et_name_4)
    EditText etName4;
    @BindView(R.id.et_name_5)
    EditText etName5;
    @BindView(R.id.et_weight_1)
    EditText etWeight1;
    @BindView(R.id.et_weight_2)
    EditText etWeight2;
    @BindView(R.id.et_weight_3)
    EditText etWeight3;
    @BindView(R.id.et_weight_4)
    EditText etWeight4;
    @BindView(R.id.et_weight_5)
    EditText etWeight5;
    @BindView(R.id.et_emnu_name)
    EditText etEmnuName;
    @BindView(R.id.et_emnu_total_weight)
    EditText etEmnuWeight;
    @BindView(R.id.lv_action)
    ListView listView;
    @BindView(R.id.root_ll)
    View root_ll;
    @BindView(R.id.tv_tips)
    TextView tvTips;

    private TopbarHelper topbarHelper;
    private OperatorItemAdapter operatorItemAdapter;
    private CookingMenu cookingMenu;
    private CookingMenu cookingMenuSrc;
    private OperatorDao operatorDao;
    private MenuFoodMaterialDao foodMaterialDao;
    private CookingMenuDao cookingMenuDao;
    private int src = 0;
    private HashMap<Integer, MenuFoodMaterial> foodMaterialHashMaps = new HashMap<>();
    private TextInputDialog textInputDialog;
    private boolean editEnable = true;
    private int foodNameIndex = 1;
    private ConfirmDialog confirmDialog;
    private SingleInputDialog singleInputDialog;
    private float gzTempSize = 0;
    private OperatorAutoHandle operatorAutoHandle;
    private DoubleSelectDialog doubleSelectDialog;
    private int cookingType = 1;
    private String paramer1;
    private String type = "M400";
    private float minWeight = 0;
    private float maxWeight = 0;
    private SelectCatgerDialog selectCatgerDialog;
    private CookingMenuMangerHelper cookingMenuMangerHelper;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_edit_menu_mirc;
    }

    @Override
    protected void initialView() {
        try {
            singleInputDialog = new SingleInputDialog(this, this);
            singleInputDialog.setEtInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
            singleInputDialog.setMiWen();
            singleInputDialog.setTips("密码");
            singleInputDialog.setHintMsg("请输入管理密码");
            textInputDialog = new TextInputDialog(this, this);
            topbarHelper = new TopbarHelper(this);
            topbarHelper.setNavActivity(CookingMenuActivity.class);
            topbarHelper.setcon(R.drawable.arrow_left);
            topbarHelper.setTitle("调整菜品");
            operatorAutoHandle = OperatorAutoHandle.getInstance(null, null, TAG);
            operatorDao = new OperatorDao(this);
            cookingMenuDao = new CookingMenuDao(this);
            cookingMenuMangerHelper = CookingMenuMangerHelper.getInstance(this, cookingMenuDao);
            selectCatgerDialog = new SelectCatgerDialog(this, this);
            foodMaterialDao = new MenuFoodMaterialDao(this);
            confirmDialog = new ConfirmDialog(this, this);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    operatorItemAdapter.setIndex(position);
                }
            });
            root_ll.setOnTouchListener(this);
            listView.setOnTouchListener(this);
            tvTips.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            doubleSelectDialog = new DoubleSelectDialog(this, this);
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }


    private void initEtView() {
        operatorItemAdapter.setEnableDelete(false);
        etEmnuName.setFocusable(editEnable);
        etName1.setFocusable(editEnable);
        etName2.setFocusable(editEnable);
        etName3.setFocusable(editEnable);
        etName4.setFocusable(editEnable);
        etEmnuWeight.setFocusable(editEnable);
    }

    @Override
    protected void initData() {
        try {
            type = Session.getSession().getString(Constant.D_GT_TYPE, "M260");
            float[] temp = getLimitValue();
            minWeight = temp[0];
            maxWeight = temp[1];
            String menuId = getIntent().getStringExtra("menuId");
            Log.e(TAG,"menuId:"+menuId);
            cookingMenu = cookingMenuDao.queryById(menuId);
            Log.e(TAG, "cookingMenu2" + JsonHelper.toJson(cookingMenu));
            src = getIntent().getIntExtra("src", 0);
            cookingMenuSrc = cookingMenu;
            if (src == 1) {
                topbarHelper.setNavActivity(StdEmnuInfoActivity.class);
            } else {
                topbarHelper.setNavActivity(EmnuInfoActivity.class);
            }
            cookingMenu.setFoodMaterials(foodMaterialDao.queryForAllByCId(cookingMenu.getId()));
            operatorItemAdapter = new OperatorItemAdapter(this, "src2");
            operatorItemAdapter.setCookingType(cookingMenu.getCookingType());
            operatorItemAdapter.setCcCookingTimeParamer(cookingMenu.getParam1());
            listView.setAdapter(operatorItemAdapter);
            cookingType = cookingMenu.getCookingType();
            paramer1 = cookingMenu.getParam1();
            operatorItemAdapter.setCcCookingTimeParamer(paramer1);
            showInfo(cookingMenu);
            initEtView();
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }


    private void showInfo(CookingMenu cookingMenu) {
        try {
            if (cookingMenu != null) {
                topbarHelper.setkey_Value("id", cookingMenu.getId());
                etEmnuName.setText(cookingMenu.getName());
                etEmnuWeight.setText(cookingMenu.getSpecification());
                operatorItemAdapter.setCookingType(cookingMenu.getCookingType());
                operatorItemAdapter.setCcCookingTimeParamer(cookingMenu.getParam1());
                initFoodMterial(cookingMenu.getId(), Float.parseFloat(cookingMenu.getSpecification()));
                float size = Float.parseFloat(cookingMenu.getSpecification());
                operatorItemAdapter.setItems(operatorDao.queryForAllByMID(cookingMenu.getId()),
                        size, false);
            }
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }


    /**
     * 初始化食材
     *
     * @param id
     */
    private void initFoodMterial(String id, float size) {
        try {
            List<MenuFoodMaterial> tempList = foodMaterialDao.queryForAllByCId(id);
            Log.e(TAG, "MenuFoodMaterials" + JsonHelper.toJson(tempList));
            for (MenuFoodMaterial foodMaterial : tempList) {
                foodMaterialHashMaps.put(foodMaterial.getNumber(), foodMaterial);
                if (foodMaterial.getNumber() == 1) {
                    etName1.setText(foodMaterial.getFoodName());
                    setEtWeight(etWeight1, foodMaterial.getWeight(), size);
                }
                if (foodMaterial.getNumber() == 2) {
                    etName2.setText(foodMaterial.getFoodName());
                    setEtWeight(etWeight2, foodMaterial.getWeight(), size);
                }
                if (foodMaterial.getNumber() == 3) {
                    etName3.setText(foodMaterial.getFoodName());
                    setEtWeight(etWeight3, foodMaterial.getWeight(), size);
                }
                if (foodMaterial.getNumber() == 4) {
                    etName4.setText(foodMaterial.getFoodName());
                    setEtWeight(etWeight4, foodMaterial.getWeight(), size);
                }
                if (foodMaterial.getNumber() == 5) {
                    etName5.setText(foodMaterial.getFoodName());
                    setEtWeight(etWeight5, foodMaterial.getWeight(), size);
                }
            }
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }

    private void setEtWeight(EditText et, long stdWeight, float size) {
        try {
            Log.e(TAG, "stdWeight:" + stdWeight + " size:" + size);
            float weight = stdWeight * size;
            et.setText(Integer.toString((int) Math.ceil(weight)));
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (requestCode == 1024) {
                String name = data.getExtras().getString(Constant.OPERATOR_NAME);
                int value = data.getExtras().getInt(Constant.OPERATOR_VALUE_1, 0);
                int value1 = data.getExtras().getInt(Constant.OPERATOR_VALUE_2, 0);
                Log.e(TAG, "name=" + name + " value1=" + value + " value2=" + value1);
                operatorItemAdapter.updateData(name, value, value1, getEtFloatValue(etEmnuWeight));
            } else if (requestCode == 1025) {
                String foodName = data.getExtras().getString(Constant.FOOD_NAME);
                int id = data.getExtras().getInt(Constant.FOOD_ID);
                if (TextUtils.equals(foodName, Constant.FOOD_NAME_DELETE) && id == 0) {
                    deleteFoods();
                    initEtName("");
                    return;
                }
                foodMaterialHashMaps.put(foodNameIndex, foodMaterialDao.queryForFoodId(id));
                initEtName(foodName);
                Log.e(TAG, "foodName:" + foodName + " foodId:" + id + " foods=" + JsonHelper.toJson(foodMaterialHashMaps));
            } else if (requestCode == 1027) {
                String paramer1 = data.getStringExtra("paramer1");
                Log.e(TAG, "paramer1:" + paramer1);
                if (paramer1 != null) {
                    this.paramer1 = paramer1;
                    operatorItemAdapter.setCcCookingTimeParamer(paramer1);
                }
            }
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }

    /**
     * 删除已保存的食材
     */
    private void deleteFoods() {
        try {
            MenuFoodMaterial menuFoodMaterial = foodMaterialHashMaps.get(foodNameIndex);
            if (menuFoodMaterial != null) {
                foodMaterialDao.delete(menuFoodMaterial);
            }
            foodMaterialHashMaps.put(foodNameIndex, null);
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }

    /**
     * 显示食材名
     *
     * @param name
     */
    private void initEtName(String name) {
        switch (foodNameIndex) {
            case 1:
                etName1.setText(name);
                break;
            case 2:
                etName2.setText(name);
                break;
            case 3:
                etName3.setText(name);
                break;
            case 4:
                etName4.setText(name);
                break;
            case 5:
                etName5.setText(name);
                break;
        }
    }


    @OnClick({R.id.tv_save, R.id.tv_tips, R.id.tv_weight_save, R.id.btn_lscc, R.id.tv_s_cat,
            R.id.et_name_1, R.id.et_name_2, R.id.et_name_3, R.id.et_name_4, R.id.et_name_5, R.id.btn_bcgdcp})
    public void onClick(View view) {
        try {
            switch (view.getId()) {
                case R.id.tv_save:
                    if (getEtFloatValue(etEmnuWeight) < 1) {
                        showLongToast("菜品总重量不能为小于1斤");
                        return;
                    }
                    confirmDialog.showDialog("是否保存修改", R.id.tv_save);
                    break;
                case R.id.tv_tips:
                    showTextInputDialog();
                    break;
                case R.id.tv_weight_save:
                    initPeratorParamers();
                    break;
                case R.id.et_name_1:
                    selectFoodMaterial(1);
                    break;
                case R.id.et_name_2:
                    selectFoodMaterial(2);
                    break;
                case R.id.et_name_3:
                    selectFoodMaterial(3);
                    break;
                case R.id.et_name_4:
                    selectFoodMaterial(4);
                    break;
                case R.id.et_name_5:
                    selectFoodMaterial(5);
                    break;
                case R.id.btn_lscc:
                    linshichaocai();
                    break;
                case R.id.tv_s_cat:
                    if (cookingMenu.getCookingType() == 0) {
                        doubleSelectDialog.showDialog(R.id.tv_s_cat);
                    } else {
                        doubleSelectResult(cookingMenu.getCookingType(), 0);
                    }
                    break;
                case R.id.btn_bcgdcp:
                    confirmDialog.showDialog("确定保存固定大小菜谱", R.id.btn_bcgdcp);
                    break;
            }
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }

    private void linshichaocai() {
        try {
            if (cookingMenu == null) {
                showLongToast("菜谱信息为空，请退回菜谱界面重新选择菜谱");
                return;
            }
            if (gzTempSize < minWeight) {
                showLongToast("不能小于" + minWeight + "斤");
                return;
            }
            if (gzTempSize > maxWeight) {
                showLongToast("不能大于" + maxWeight + "斤");
                return;
            }
            cookingMenu.setSpecification(Float.toString(gzTempSize));
            Intent intent1 = new Intent(this, CookingActivity.class);
            intent1.putExtra("cookingMenu", JsonHelper.toJson(cookingMenu));
            intent1.putExtra("operators", JsonHelper.toJson(operatorItemAdapter.getData()));
            startActivity(intent1);
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }

    /**
     * 选择食材
     *
     * @param id
     */
    private void selectFoodMaterial(int id) {
        try {
            foodNameIndex = id;
            Intent intent = new Intent(this, FoodMaterialActivity.class);
            intent.putExtra("src_class", 3);
            startActivityForResult(intent, 1025);
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }


    /**
     * 保存菜谱信息
     */
    private void saveEmnu() {
        try {
            if(!NumToStringUtil.isInteger(getEtString(etEmnuWeight))){
                showLongToast("重量请输入正整数");
                return;
            }
            etEmnuName.setText(getEtString(etEmnuName).toUpperCase());
            if (TextUtils.isEmpty(getEtString(etEmnuName))) {
                showLongToast("请输入菜品名称");
                return;
            }
            if (!cookingMenuMangerHelper.isHasCat(getEtString(etEmnuName))) {
                showLongToast("菜谱名称要包含分类组合字母");
                selectCatgerDialog.showDialog(cookingMenuMangerHelper.getCatLists());
                return;
            }
            if (TextUtils.isEmpty(getEtString(etEmnuName))) {
                showLongToast("请输入菜品名称");
                return;
            }
            if (TextUtils.isEmpty(getEtString(etEmnuWeight))) {
                showLongToast("菜品总重量不能为0");
                return;
            }
            if (checkEt()) {
                return;
            }
            if (checkOperator()) {
                showLongToast("请填入有效操作");
                return;
            }
            singleInputDialog.showDialog(1);
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }

    private void saveGdcp() {
        try {
            if(!NumToStringUtil.isInteger(getEtString(etEmnuWeight))){
                showLongToast("重量请输入正整数");
                return;
            }
            etEmnuName.setText(getEtString(etEmnuName).toUpperCase());
            if (TextUtils.isEmpty(getEtString(etEmnuName))) {
                showLongToast("请输入菜品名称");
                return;
            }
            if (!cookingMenuMangerHelper.isHasCat(getEtString(etEmnuName))) {
                showLongToast("菜谱名称要包含分类组合字母");
                selectCatgerDialog.showDialog(cookingMenuMangerHelper.getCatLists());
                return;
            }
            if (TextUtils.isEmpty(getEtString(etEmnuName))) {
                showLongToast("请输入菜品名称");
                return;
            }
            if (TextUtils.isEmpty(getEtString(etEmnuWeight))) {
                showLongToast("菜品总重量不能为0");
                return;
            }
            if (gzTempSize < 1) {
                showLongToast("菜品总重量不能小于1");
                return;
            }
            if (gzTempSize!= getEtFloatValue(etEmnuWeight)) {
                showLongToast("请点击右上角的自动计算");
                return;
            }
            if (checkEt()) {
                return;
            }
            if (checkOperator()) {
                showLongToast("请填入有效操作");
                return;
            }
            singleInputDialog.showDialog(2);
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }


    /**
     * 计算菜谱时长
     *
     * @param list
     * @return
     */
    private int getTotalCostTime(List<Operator> list) {
        return operatorAutoHandle.getOperDuring(list);
    }

    /**
     * 判断操作的有效性
     *
     * @return
     */
    private boolean checkOperator() {
        try {
            boolean temp = false;
            for (Operator operator : operatorItemAdapter.getData()) {
                if (!TextUtils.isEmpty(operator.getName()) &&
                        TextUtils.equals(operator.getName(), "请选择")) {
                    showLongToast("请填入有效操作");
                    return true;
                }
                if (operator.getDelayTime() <= 0) {
                    showLongToast("时间不能为0");
                    return true;
                }
                if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_CCSC)) {
                    temp = true;
                }
            }
            if (!temp) {
                showLongToast("请添加炒菜时长指令，炒菜步骤中必须含有炒菜时长该指令");
                return true;
            }
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
        return false;
    }

    /**
     * 检查字段有效性
     *
     * @return
     */
    private boolean checkEt() {
        try {
            String names = getEtString(etName1) + getEtString(etName2) + getEtString(etName3) + getEtString(etName4) + getEtString(etName5);
            if (TextUtils.isEmpty(names)) {
                showLongToast("素材名字不能全部为空");
                return true;
            }
            float weights = getEtFloatValue(etWeight1) + getEtFloatValue(etWeight2) + getEtFloatValue(etWeight3) +
                    getEtFloatValue(etWeight4) + getEtFloatValue(etWeight5);
            if (weights <= 0) {
                showLongToast("素材重量不能全部为0");
                return true;
            }
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
        return false;
    }

    /**
     * 获取输入框的内容
     *
     * @param et
     * @return
     */
    private String getEtString(EditText et) {
        return et.getText().toString().trim();
    }


    /**
     * 获取输入框的数字值
     *
     * @param et
     * @return
     */
    private float getEtFloatValue(EditText et) {
        try {
            String ss = et.getText().toString().trim();
            if (TextUtils.isEmpty(ss)) {
                return 0f;
            }
            return Float.parseFloat(ss);
        } catch (Exception e) {
            showShortToast("请输入有效数字，数据转换异常");
        }
        return 0f;
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        try {
            if (null != MiroEditMenuActivity.this.getCurrentFocus()) {
                InputMethodManager manager = (InputMethodManager) MiroEditMenuActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (manager != null) {
                    return manager.hideSoftInputFromWindow(MiroEditMenuActivity.this.getCurrentFocus().getWindowToken(), 0);
                }
            }
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
        return false;
    }

    /**
     * 获取菜谱食材内容
     *
     * @return
     */
    private List<MenuFoodMaterial> getFoodMaterial() {
        List<MenuFoodMaterial> list = new ArrayList<>();
        try {
            if (foodMaterialHashMaps.containsKey(GZ_1)) {
                MenuFoodMaterial temp = foodMaterialHashMaps.get(GZ_1);
                if (temp != null) {
                    temp.setId(getFoodsId(cookingMenu.getId(), GZ_1));
                    temp.setCid(cookingMenu.getId());
                    temp.setNumber(GZ_1);
                    temp.setWeight((int) getEtFloatValue(etWeight1));
                    temp.setType(Constant.FOODS_TYPE_2);
                    list.add(temp);
                } else {
                    Log.e(TAG, "GZ_1==null");
                }
            }
            if (foodMaterialHashMaps.containsKey(GZ_2)) {
                MenuFoodMaterial temp = foodMaterialHashMaps.get(GZ_2);
                if (temp != null) {
                    temp.setType(Constant.FOODS_TYPE_2);
                    temp.setId(getFoodsId(cookingMenu.getId(), GZ_2));
                    temp.setNumber(GZ_2);
                    temp.setWeight((int) getEtFloatValue(etWeight2));
                    temp.setCid(cookingMenu.getId());
                    list.add(temp);
                } else {
                    Log.e(TAG, "GZ_2==null");
                }
            }
            if (foodMaterialHashMaps.containsKey(GZ_3)) {
                MenuFoodMaterial temp = foodMaterialHashMaps.get(GZ_3);
                if (temp != null) {
                    temp.setType(Constant.FOODS_TYPE_2);
                    temp.setId(getFoodsId(cookingMenu.getId(), GZ_3));
                    temp.setNumber(GZ_3);
                    temp.setWeight((int) getEtFloatValue(etWeight3));
                    temp.setCid(cookingMenu.getId());
                    list.add(temp);
                } else {
                    Log.e(TAG, "GZ_3==null");
                }
            }
            if (foodMaterialHashMaps.containsKey(GZ_4)) {
                MenuFoodMaterial temp = foodMaterialHashMaps.get(GZ_4);
                if (temp != null) {
                    temp.setId(getFoodsId(cookingMenu.getId(), GZ_4));
                    temp.setCid(cookingMenu.getId());
                    list.add(temp);
                    temp.setWeight((int) getEtFloatValue(etWeight4));
                    temp.setNumber(GZ_4);
                    temp.setType(Constant.FOODS_TYPE_2);
                } else {
                    Log.e(TAG, "GZ_4==null");
                }
            }
            if (foodMaterialHashMaps.containsKey(GZ_5)) {
                MenuFoodMaterial temp = foodMaterialHashMaps.get(GZ_5);
                if (temp != null) {
                    temp.setId(getFoodsId(cookingMenu.getId(), GZ_5));
                    temp.setCid(cookingMenu.getId());
                    list.add(temp);
                    temp.setWeight((int) getEtFloatValue(etWeight5));
                    temp.setNumber(GZ_5);
                    temp.setType(Constant.FOODS_TYPE_2);
                } else {
                    Log.e(TAG, "GZ_5==null");
                }
            }
            for (int i = 0; i < list.size(); i++) {
                MenuFoodMaterial menuFoodMaterial = list.get(i);
                float weight = Float.parseFloat(getEtString(etEmnuWeight));
                float stdW = menuFoodMaterial.getWeight() / (float)weight;
                menuFoodMaterial.setWeight((int) Math.round(stdW));
            }
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
        Log.e(TAG, "菜谱食材：" + JsonHelper.toJson(list));
        return list;
    }

    @Override
    public void textInputResult(String value, int id) {
        Log.e(TAG, "食材处理要求:" + value);
        cookingMenu.setDesc(value);
    }

    /**
     * 显示食材说明输入框
     */
    private void showTextInputDialog() {
        try {
            if (textInputDialog != null && cookingMenu != null) {
                textInputDialog.setTitle("食材处理要求");
                textInputDialog.setEditText1(cookingMenu.getDesc());
                textInputDialog.showDialog(1);
            } else {
                showLongToast("数据异常，请返页面重新打开");
            }
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }

    /**
     * 检查步骤时长有效性
     */
    private void initPeratorParamers() {
        try {
            float value = getEtFloatValue(etEmnuWeight);
            Log.e(TAG, "value=" + value);
            if (value <= 0) {
                showLongToast("非法数据，请输入有效浮点数");
                return;
            }
            if (value < 1) {
                showLongToast("不能小于0斤");
                return;
            }
            gzTempSize = value;
            operatorItemAdapter.setItems(operatorAutoHandle.changgeOperator(
                    operatorDao.queryForAllByMID(cookingMenu.getId()), value, paramer1, cookingType));
            initFoodMterial(cookingMenu.getId(), value);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            showLongToast("数据解析异常");
            finish();
        }
    }

    /**
     * 获取食品id
     *
     * @param cid
     * @param num
     * @return
     */
    private String getFoodsId(String cid, int num) {
        return cid.substring(0, cid.length() - 1) + num;
    }

    @Override
    public void selectResult(int value, int id) {
        if (value == 1) {
            if (id == R.id.tv_save) {
                saveEmnu();
            } else if (id == R.id.btn_bcgdcp) {
                saveGdcp();
//                showLongToast("待开发");
            }
        }
    }

    @Override
    public void SingleDialogInputResult(String value, int id) {
        try {
            LocalUserDao localUserDao = new LocalUserDao(this);
            LocalUser localUser = localUserDao.queryForId(UuidUtil.getUuidByName(Constant.USER_NAME));
            if (localUser == null) {
                showLongToast("用户不存在,请联系管理员");
                return;
            }
            if (!TextUtils.equals(value, localUser.getPwd())) {
                showLongToast("输入的密码错误");
                return;
            }

            if (id == 1) {
                saveNormalMenu();
            } else if (id == 2) {
                saveFNormalMenu();
            }

        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }

    private void saveNormalMenu() {
      try {
          boolean isNew = false;
          if (!TextUtils.equals(cookingMenuSrc.getName(), getEtString(etEmnuName))) {
              Log.e(TAG, "生成新的菜谱");
              cookingMenu.setId(UuidUtil.getUuid() + "_" + cookingMenu.getMachineModoel());
              cookingMenu.setName(getEtString(etEmnuName));
              isNew = true;
          }
          if (isNew && checkFoodMeters()) {
              showLongToast("食材不能和原有食材一致");
              return;
          }
          cookingMenu.setSpecification("1");
          cookingMenu.setParam1(paramer1);
          cookingMenu.setCookingType(cookingType);
          cookingMenu.setFoodMaterials(getFoodMaterial());
          cookingMenu.setOperators(setMId(cookingMenu.getId()));
          cookingMenu.setDuration(getTotalCostTime(cookingMenu.getOperators()));
          cookingMenu.setType(Constant.MENU_NORMAL);
          cookingMenu.setUploaded(0);
          cookingMenu.setUpdateTime(TimeUtils.getCurrrentTimeYMDHMS());
          cookingMenuDao.createOrUpdateAll(cookingMenu);
          initFoodMenuInfo(cookingMenu.getId());
          showInfo(cookingMenuSrc);
          cookingMenuMangerHelper.updateCookingMenu(cookingMenuSrc);
          showLongToast("修改成功");
      }catch (Exception e){
          Log.e(TAG,"saveNormalMenu:"+e.getMessage());
          showLongToast("保存失败:"+e.getMessage());
      }
    }

    private void saveFNormalMenu() {
        try {
            boolean isNew = false;
            if (!TextUtils.equals(cookingMenuSrc.getName(), getEtString(etEmnuName))) {
                Log.e(TAG, "生成新的菜谱");
                cookingMenu.setId(UuidUtil.getUuid() + "_" + cookingMenu.getMachineModoel());
                cookingMenu.setName(getEtString(etEmnuName));
                isNew = true;
            }
            if (isNew && checkFoodMeters()) {
                showLongToast("食材不能和原有食材一致");
                return;
            }
            String id = getIdSpit(cookingMenu.getId()) + cookingMenu.getMachineModoel() + Integer.toString((int) gzTempSize);
            cookingMenu.setId(id);
            cookingMenu.setSpecification(Integer.toString((int) gzTempSize));
            cookingMenu.setParam1(paramer1);
            cookingMenu.setCookingType(cookingType);
            cookingMenu.setFoodMaterials(getFoodMaterial());
            cookingMenu.setOperators(operatorItemAdapter.getData());
            cookingMenu.setType(Constant.MENU_NORMAL);
            cookingMenu.setUploaded(0);
            cookingMenu.setUpdateTime(TimeUtils.getCurrrentTimeYMDHMS());
            cookingMenuDao.createOrUpdateAll(cookingMenu);
            cookingMenuMangerHelper.updateCookingMenu(cookingMenu);
            showLongToast("固定规定菜谱保存成功");
        }catch (Exception e){
            showLongToast("保存失败:"+e.getMessage());
            Log.e(TAG,"saveFNormalMenu:"+e.getMessage());
        }
    }

    private String getIdSpit(String cid){
        int index=cid.indexOf("_");
        if(index!=-1){
         return cid.substring(0,index+1);
        }
        return cid;
    }

    private void initFoodMenuInfo(String id) {
        cookingMenuSrc = cookingMenuDao.queryById(id);
    }

    /**
     * 判断有没有修改食材
     *
     * @return
     */
    private boolean checkFoodMeters() {
        boolean temp = false;
        try {
            List<MenuFoodMaterial> datas = cookingMenu.getFoodMaterials();
            if (datas == null || datas.isEmpty()) {
                return false;
            }
            HashMap<String, String> tempHashMap = new HashMap<>();
            HashMap<String, String> tempHashMap2 = new HashMap<>();
            for (MenuFoodMaterial menuFoodMaterial : datas) {
                tempHashMap.put(menuFoodMaterial.getFoodName(), menuFoodMaterial.getFoodName());
            }
            if (!TextUtils.isEmpty(getEtString(etName1))) {
                tempHashMap2.put(getEtString(etName1), getEtString(etName1));
            }
            if (!TextUtils.isEmpty(getEtString(etName2))) {
                tempHashMap2.put(getEtString(etName2), getEtString(etName2));
            }
            if (!TextUtils.isEmpty(getEtString(etName3))) {
                tempHashMap2.put(getEtString(etName3), getEtString(etName3));
            }
            if (!TextUtils.isEmpty(getEtString(etName4))) {
                tempHashMap2.put(getEtString(etName4), getEtString(etName4));
            }
            if (tempHashMap.equals(tempHashMap2)) {
                temp = true;
            }
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
        return temp;
    }

    private List<Operator> setMId(String id) {
        int duration = 0;
        List<Operator> data = new ArrayList<>();
        try {
            float weight = getEtFloatValue(etEmnuWeight);
            List<Operator> list = OperatorAutoHandle.getInstance(null, null, TAG)
                    .changgeOperator(operatorItemAdapter.getData(), 1 / weight, paramer1, cookingType);
            int num = 1;
            for (Operator operator : list) {
                operator.setmId(id);
                operator.setNum(num);
                data.add(operator);
                num++;
                duration += operator.getDelayTime();
            }
            cookingMenu.setDuration(duration);
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
        return data;
    }

    @Override
    public void doubleSelectResult(int value1, int id) {
        try {
            Log.e(TAG, "选择:" + value1);
            cookingType = value1;
            Intent intent = new Intent(this, CookingMenParamersSettingActivity.class);
            intent.putExtra("cookingType", value1);
            intent.putExtra("code", 1027);
            intent.putExtra("paramer1", paramer1);
            startActivityForResult(intent, 1027);
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }

    private float[] getLimitValue() {
        float[] temp = new float[2];
        if (TextUtils.equals(type, "M600")) {
            temp[0] = 5f;
            temp[1] = 80f;
        }
        if (TextUtils.equals(type, "M400")) {
            temp[0] = 4f;
            temp[1] = 40f;
        }
        if (TextUtils.equals(type, "M260")) {
            temp[0] = 0.5f;
            temp[1] = 7f;
        }
        return temp;
    }

    @Override
    public void selectCatgerDialogResult(String catName, int cookingType) {
        if (catName.contains("Z")) {
            showShortToast("不能选择该类型");
            return;
        }
        if (cookingType == 1 && !catName.contains("X")) {
            showShortToast("炒菜类型和字母标签不符，请选择带X的标签");
            return;
        }
        if (cookingType == 2 && !catName.contains("Y")) {
            showShortToast("炒菜类型和字母标签不符，请选择带Y的标签");
            return;
        }
        etEmnuName.setText(getEtString(etEmnuName) + catName);
    }
}